#!/bin/env python
"""

Issues:
 - The URL passed to ServerProxy should come from a config file
 - The file containing the server cert trust change should come from a config file
"""
#import getpass
import httplib
#import pdb
#import pprint
import socket
import ssl
# import sys
import xmlrpclib
from OpenSSL import SSL


class TLSv1Transport(xmlrpclib.Transport):
    def __init__(self, use_datetime=0, keyfile=None, certfile=None):
        self.keyfile = keyfile
        self.certfile = certfile
        xmlrpclib.Transport.__init__(self, use_datetime)
        
    def make_connection(self, host):
        # create a HTTPS connection object from a host descriptor
        # host may be a string, or a (host, x509-ndict) tuple
        # import httplib
        host, extra_headers, x509 = self.get_host_info(host)
        try:
            HTTPS = TLSv1_HTTPS
        except AttributeError:
            raise NotImplementedError(
                "your version of httplib doesn't support HTTPS"
                )
        else:
            return HTTPS(host, None, **(x509 or {}))

class TLSv1_HTTPSConnection(httplib.HTTPSConnection):
    def connect(self):
        sock = socket.create_connection((self.host, self.port), self.timeout)
        if self._tunnel_host:
            self.sock = sock
            self._tunnel()
        self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
                                    ssl_version=ssl.PROTOCOL_TLSv1,
                                    ca_certs='server/scert.pem',
                                    cert_reqs=ssl.CERT_REQUIRED)
        self.sock.do_handshake()
        
class TLSv1_HTTPS(httplib.HTTPS):
    _connection_class = TLSv1_HTTPSConnection
